const app = getApp()

Page({ /* 页面的初始数据 */
  data: { /* 将types数组赋值给cateItems */

    curNav: 0,
    /* 此变量用于判断该显示某个子item */
    curIndex: 0,
    foodname: '',
    num: 0, //选餐数量
    showBottomPopup: false,
    showPopup: false,
    duration: 3000,
    foodList: [], //菜品分类,
    food: [],
    desk: '',
    billid: '', //账单id
    restaurantid: '', //餐厅id
    urls: '', //圖片地址,
    scrollTop: 0,
    srollHeight: 450, //给的一个初始高度
    bill_ids: '', //外卖订单id
    types: '', //选餐方式
    decrease: true, //减号隐藏
    categoryId:'',
    count: true, //数量隐藏
    deskId: '', //桌台id
    billTotal: '0.00', //总价
    gouwucheList: [], //购物车列表
    lenthList: 0,
    deletsbill: '',
    clickTimes: 'true',
    hidden: 'false',
    food_name: 0, //商品数量,
    scan_url:'',//二维码路径
    $zanui: {
      toptips: {
        show: false
      }
    },
  },
  //   返回首页
  e_gohome: function() {
    console.log('跳转')
    wx.switchTab({
      url: '../index/index',
    })
  },
  //防止连点
  clickTime() {
    var that = this
    setTimeout(() => {
      this.setData({
        clickTimes: 'true'
      });
      console.log('点击倒计时', that.data.clickTimes)
    }, 3000);

  },
  onShow() {},
  //外卖订餐从选择就餐方式页面生成账单id 传值   店内就餐是加载菜品分类时产生的账单id
  onLoad(options) {
    var that = this
    console.log('asdasdasdasdasdasdasdasasd',options)
    if (options.q !== undefined) {

      var scan_url = decodeURIComponent(options.q);
      that.setData({
        scan_url: scan_url
      })
    }
    that.islogin(options)
    that.shop_card()
  },
  //扫码点餐
  getLuckSum(scan_url) {
    var _this = this
    setTimeout(function() {
      _this.wxScanCode(scan_url)
    }, 2000)
  },
  wxScanCode(scan_url) {
    var that = this
    var userid = app.globalDataO.openid.objectSid
    console.log(userid)
    wx.request({
      url: scan_url + '&memberId=' + userid + '&seats=1' + '&type=1',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        console.log('哈哈哈哈哈哈哈哈',res)
        var deskId = res.data.deskId
        var restaurantId = res.data.restaurantId
        that.setData({
          restaurantid: restaurantId,
          types: 1
        })
        that.getTs(deskId, restaurantId)
      }
    })
  },
  // 
  //外卖选餐
  getWm(restaurantId, bill_id) {
    var that = this
    app.gets(app.url.indexTwo + '?restaurantId=' + restaurantId + '&bill_id=' + bill_id).then(res => {
      console.log(res)
      if (res.data.category == "" || res.data.category == null || res.data.category == undefined) {
        that.setData({
          hidden: 'true'
        })
        return false;
      }
      console.log(res)
      console.log(res.data.category)
      var categoryId = res.data.category[0].OBJECT_SID;
      that.setData({
        categoryId: categoryId,
        foodList: res.data.category,
        foodname: res.data.category[0].NAME,
        billid: res.data.bill.objectSid,
        urls: res.data.urls,
        hidden: 'true',
        categoryId:categoryId
      })
      that.getFoods(categoryId)
    })
  },
  //堂食选餐
  getTs(deskId, restaurantId) {
    var that = this
    app.gets(app.url.desk + '?restaurantId=' + restaurantId + '&deskId=' + deskId).then(res => {
      if (res.data.category == "" || res.data.category == null || res.data.category == undefined) {
        that.setData({
          hidden: true
        })
        return false;
      }
      console.log('这是堂内选餐',res)
      var categoryId = res.data.category[0].OBJECT_SID;
      console.log('这是什么id',categoryId)
      that.setData({
        categoryId: categoryId,
        foodList: res.data.category,
        foodname: res.data.category[0].NAME,
        billid: res.data.bill[0].OBJECT_SID,
        urls: res.data.urls,
        hidden: 'true'
      })
      that.getFoods(categoryId)
    })
  },
  // 获取食品分类信息
  switchRightTab: function(e) {
    var that = this
    let index = e.target.dataset.index;
    var categoryId = e.target.dataset.id;
    var foodname = e.target.dataset.foodname;
    console.log(categoryId, foodname)
    that.setData({
      categoryId: categoryId,
      curNav: index,
      foodname: foodname,
    })
    that.getFoods()
  },

  toggleBottomPopup() {
    if (this.data.gouwucheList.length == 0) {
      return
    }
    this.setData({
      showBottomPopup: !this.data.showBottomPopup
    });
    this.shop_card()
    this.getFoods(this.data.categoryId)
  },
  // 获取食品信息
  getFoods(categoryId) {
    var that = this
    let nums = []
    var billid = that.data.billid
    var restaurantid = that.data.restaurantid
    app.gets(app.url.categoryList + '?categoryId=' + that.data.categoryId + '&billId=' + billid + '&restaurantId=' + restaurantid).then(res => {
      console.log('这是菜品数量',res)
      // for (var i = 0; i < res.data.food.length; i++) {
      //   nums[i] = {
      //     spid: res.data.food[i].OBJECT_SID,
      //     xnum: 0
      //   };
      // }
      that.setData({
        food: res.data.food,
        num: nums
      })
    })
  },
  settle() {
    wx.navigateTo({
      url: '../../pages/balance-store/store',
    })
  },
  //授权
  getuserInfo1(){
    var that=this
    wx.getUserInfo({
      success(res){
        console.log('点击了允许')
        that.setData({
          showPopup: false
        })
        that.getUserid()
      }
    })
  },
  //获取userid
  getUserid(){
    let that = this;
    wx.login({
      success: res => {
        // console.log(res)
        if (res.code) {
          wx.request({
            url: app.url.logins,
            data: {
              code: res.code
            },
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            method: 'POST',
            success: res => {
              var openid = res.data
              var sessionKey = res.data.sessionKey
              that.getUser(openid, sessionKey)
              //储存返回的openid
            }
          })
        } else {
          // console.log('获取用户登录态失败！' + res.errMsg);
          reject('error');
        }
      }
    })
  },
  // 获取用户信息
  getUser: function (openid, sessionKey) {
    var that = this
    return new Promise(function (resolve, reject) {
            wx.getUserInfo({
              success: res => {
                resolve(res)
                console.log(res)
                if (res.userInfo) {
                  var encryptedData  = res.encryptedData
                  var iv= res.iv
                  return new Promise(function (resolve, reject) {
                    wx.request({
                      url: app.url.getuserId,
                      method: 'GET',
                      header: {
                        'content-type': 'application/json',
                      },
                      data: {
                        encryptedData:encryptedData,
                        sessionKey:sessionKey,
                        iv:iv,
                        userId:''
                      },
                      success(res) {
                            app.globalDataO.openid['objectSid'] = res.data.objectSid
                        if (that.data.scan_url) {
                          that.getLuckSum(that.data.scan_url)
                        } else {
                          let id = options.id
                          let bill_id = options.bill_id
                          let deskId = options.deskId
                          let restaurantId = options.restaurantId
                          let types = options.types
                          that.setData({
                            types: types,
                            restaurantid: restaurantId,
                            deletsbill: bill_id,
                            deskId: deskId
                          })
                          console.log(bill_id + '选餐方式' + types)
                          console.log('餐厅id' + restaurantId + '餐台id' + deskId)
                          if (types == 2) {
                            that.getTs(deskId, restaurantId)
                          } else {
                            that.getWm(restaurantId, bill_id)
                          }
                        }
                      }
                    })
                  })
                } else {
                  wx.showToast({
                    title: '网络出错',
                  })
                }
                // console.log(that.globalData.userInfo)
                if (that.userInfoReadyCallback) {
                  that.userInfoReadyCallback(res)
                }
              },
            })
  
        

    })
  },
  //计算数量
  jian(e) {
    var that = this
    var sum = e.currentTarget.dataset.sum
    var index = 0
    var nums = that.data.num
    let billId = that.data.billid
    var price = e.currentTarget.dataset.price
    var caiid = e.currentTarget.dataset.caiid
    var add = (e.currentTarget.dataset.add)

    // nums.forEach((item, i) => {
    //   if (item.spid == caiid) {
    //     index = i
    //   }
    // })

    // if (nums[index].xnum <= 0) {
    //   that._topCue('数量不能少于0')
    //   return
    // }

    // nums[index].xnum--
    //   that.setData({
    //     num: nums
    //   })

    add = parseInt(add)
    console.log(price, caiid, add)
    app.post(app.url.updateBillLine, {
      billId: billId,
      type: add,
      foodId: caiid,
      unitPrice: price
    }).then(res => {
      that.shop_card()
      this.getFoods(that.data.categoryId)
    })

  },

  //判断登录状态
  islogin(options) {
    var that = this
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.userInfo']) {
          if (that.data.scan_url) {
            that.getLuckSum(that.data.scan_url)
          } else {
            let id = options.id
            let bill_id = options.bill_id
            let deskId = options.deskId
            let restaurantId = options.restaurantId
            let types = options.types
            that.setData({
              types: types,
              restaurantid: restaurantId,
              deletsbill: bill_id,
              deskId: deskId
            })
            console.log(bill_id + '选餐方式' + types)
            console.log('餐厅id' + restaurantId + '餐台id' + deskId)
            if (types == 2) {
              that.getTs(deskId, restaurantId)
            } else {
              that.getWm(restaurantId, bill_id)
            }
          }
        } else {
          console.log('见咯')
          that.setData({
            showPopup: true,
            hidden:'true'
          })
          return false;
        }

      },
    })
  },
  //正常外卖点餐
  //添加
  add(e) {
    console.log(e.currentTarget.dataset)
    var that = this
    var nums = that.data.num;
    var index = e.currentTarget.dataset.index
    // console.log(index)
    // var zheng = 1
    // nums[index].xnum++
    //   that.setData({
    //     num: nums
    //   })
    let billId = that.data.billid
    var price = e.currentTarget.dataset.price
    var caiid = e.currentTarget.dataset.caiid
    var add = (e.currentTarget.dataset.add)
    add = parseInt(add)
    console.log(price, caiid, add)
    app.post(app.url.updateBillLine, {
      billId: billId,
      type: add,
      foodId: caiid,
      unitPrice: price
    }).then(res => {
      console.log('sadasd',res)
      that.shop_card()
      this.getFoods(that.data.categoryId)
    })

  },
  //评论
  e_comment(e) {
    var id = this.data.restaurantid
    console.log(id)
    wx.navigateTo({
      url: '../../pages/commetn_list/commetn_list?id=' + id,
    })
  },
  //购物车详情
  shop_card() {
    var that = this
    app.post(app.url.billLine, {
      billId: this.data.billid
    }).then(res => {
      console.log('购物陈详情',res)
      if (res.data.billLine == "" || res.data.billLine == null) {
        that.setData({
          gouwucheList: [],
          billTotal: 0,
          lenthList: 0,
          showBottomPopup: false,
         
        })
        return;
      } else {
        that.setData({
          gouwucheList: res.data.billLine,
          food_name: res.data.billLine[0].FOOD_NUM,
          billTotal: res.data.billLine[0].billTotal,
          lenthList: res.data.numTotal
        })
      }

    })
  },
  //购物车减
  jiancard(e) {
    let that = this
    let billId = that.data.billid
    var price = e.currentTarget.dataset.price
    var caiid = e.currentTarget.dataset.caiid
    var add = (e.currentTarget.dataset.add)
    add = parseInt(add)
    console.log(price, caiid, add)
    app.post(app.url.updateBillLine, {
      billId: billId,
      type: add,
      foodId: caiid,
      unitPrice: price
    }).then(res => {
      that.shop_card()
      this.getFoods(that.data.categoryId)
    })
  },
  //清空购物车
  deletes() {
    var that = this
    let billId = that.data.billid
    let restaurantId = that.data.restaurantid
    let bill_id = that.data.deletsbill
    let deskId = that.data.deskId
    let unm = that.data.num
    app.post(app.url.deletesbillLine, {
      billId: billId
    }).then(res => {
      // unm.forEach(item => {
      //   item.xnum = 0
      // })
      // that.setData({
      //   num: unm
      // })
      that.shop_card()
      this.getFoods(that.data.categoryId)
    })
  },
  //处理防连点结算
  seatprice() {
    if (this.data.clickTimes == 'true') {
      this.data.clickTimes = 'false'
      this.clickTime()
      this.seatprice1()
    } else {
      console.log('请不要多次点击')
    }
  },
  //结算
  seatprice1() {
    var that = this

    if (this.data.gouwucheList.length == 0) {
      that._topCue('请选择产品')
      return
    }
    let billId = that.data.billid
    app.post(app.url.seatprice, {
      bill_id: this.data.billid,
      restaurant_id: this.data.restaurantid,
      customerMoney: this.data.billTotal

    }).then(res => {
      console.log(res)
      let price = res.data.price
      let totalprice = res.data.totalprice
      let order = res.data.order
      console.log(order, totalprice)
      if (that.data.types == 2) {
        wx.navigateTo({
          url: '../../pages/balance-store/store?price=' + price + '&totalprice=' + totalprice + '&billId=' + billId + '&restaurantId=' + that.data.restaurantid + '&order=' + order + '&types=' + that.data.types,
        })
      }
      if (that.data.types == 1) {
        wx.navigateTo({
          url: '../../pages/balance-store/store?price=' + price + '&totalprice=' + totalprice + '&billId=' + billId + '&restaurantId=' + that.data.restaurantid + '&order=' + order + '&types=' + that.data.types,
        })
      }
      if (that.data.types == 4) {
        wx.navigateTo({
          url: '../../pages/side_food/food?price=' + price + '&totalprice=' + totalprice + '&billId=' + billId + '&restaurantId=' + that.data.restaurantid + '&order=' + order + '&types=' + that.data.types,
        })
      }

    })
  },
  _topCue: function(text) {
    this.setData({
      content: text,
      $zanui: {
        toptips: {
          show: true
        }
      }
    });
    setTimeout(() => {
      this.setData({
        $zanui: {
          toptips: {
            show: false
          }
        }
      });
    }, this.data.duration);
  },

})